package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.dtos.RegisteredDto;
import com.heima.model.user.dtos.UserDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.common.RegexUtils;
import com.heima.utils.common.SendSms;
import com.heima.utils.common.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpSession;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Slf4j
@Service
@Transactional
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    /**
     * 用户登录
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.正常登录
        if (!StringUtils.isBlank(dto.getPhone()) && !StringUtils.isBlank(dto.getPassword())) {
            //1.1根据手机号查询数据库
            LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
            lqw.eq(ApUser::getPhone, dto.getPhone());
            ApUser apUser = getOne(lqw);
            //2.根据判断用户是否存在
            if (apUser == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在");
            }
            //3.判断密码是否正确
            String salt = apUser.getSalt();  //盐
            String password = apUser.getPassword();
            String pasw = DigestUtils.md5DigestAsHex((salt + dto.getPassword()).getBytes());
            if (!pasw.equals(password)) {
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            //4.返回数据
            Map<String, Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(apUser.getId().longValue());
            map.put("token", token);
            //4.1保证数据安全，返回时设置盐和密码为空
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user", apUser);
            return ResponseResult.okResult(map);

        } else {
            //5.游客登录
            Map<String, Object> map = new HashMap<>();
            String token = AppJwtUtil.getToken(0L);
            map.put("token", token);
            return ResponseResult.okResult(map);
        }
    }

    /**
     * 用户注册校验
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult registered(RegisteredDto dto, HttpSession session) {
        //1.获取session中的验证码
        String code = (String) session.getAttribute("phone");
        //2.获取用户输入的验证码
        String verification = dto.getVerification();
        if (verification.equals(code)) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.valueOf("验证码输入错误"));
    }

    /**
     * 短信发送
     *
     * @param phone
     * @return
     */
    @Override
    public ResponseResult sendMsg(String phone, HttpSession session) {
        //1.校验手机号正确性
        boolean flag = RegexUtils.isChinaPhoneLegal(phone);
        if (!flag) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "手机号格式错误");
        }
        //2.生成验证码
        String code = ValidateCodeUtils.generateValidateCode4String(4);
        //3.将验证码保存在session中
        session.setAttribute("phone", code);
        //4.发送短信
        try {
            SendSms.sendMsg(phone, code);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseResult.errorResult(AppHttpCodeEnum.valueOf("短信发送失败"));
        }

    }

    /**
     * 注册新用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult addApUser(UserDto dto,String phone) {
        //1.根据用户输入的账户查询数据库中是否存在该用户
        String name = dto.getName();
        LambdaQueryWrapper<ApUser> lqw = new LambdaQueryWrapper<>();
        lqw.eq(ApUser::getName, name);
        ApUser apUser = getOne(lqw);
        if (apUser != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"账户已存在");
        }
        //2.比对用户输入的两次密码是否一致
        if(!dto.getPassword().equals(dto.getPowd())){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"密码输入不一致，请检查");
        }
        //3.添加用户
        ApUser user = new ApUser();
        //3.1生成随机盐
        String salt = UUID.randomUUID().toString().replace("-", "");
        //3.2密码加密
        String password = DigestUtils.md5DigestAsHex((dto.getPassword() + salt).getBytes(StandardCharsets.UTF_8));
        user.setName(dto.getName());
        user.setSalt(salt);
        user.setPassword(password);
        user.setStatus(true);
        user.setPhone(phone);
        user.setFlag(0);
        save(user);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
